﻿namespace com.stifel.BranchMgmt
{
    using System;
    using System.Collections.Generic;

    using com.stifel.BranchMgmtDao;
    using com.stifel.SharePoint;

    using Microsoft.SharePoint.Administration;

    public partial class SunsetHardwareScheduledMaintenance : SPJobDefinition
    {
        #region Fields

        public const string JOBTITLE = "SunsetHardwareScheduledMaintenance";

        StifelSunsetBranchInfoConfiguration _configuration;

        #endregion Fields

        #region Constructors

        public SunsetHardwareScheduledMaintenance( )
            : base()
        {
        }

        public SunsetHardwareScheduledMaintenance( string name, SPWebApplication webApplication )
            : base(name, webApplication, null, SPJobLockType.Job)
        {
        }

        #endregion Constructors

        #region Properties

        StifelSunsetBranchInfoConfiguration configuration
        {
            get
            {
                if ( _configuration == null )
                {
                    StifelSunsetBranchInfoConfigurationDao dao = new StifelSunsetBranchInfoConfigurationDao( );
                    _configuration = dao.Get( );
                }
                return _configuration;
            }
        }

        #endregion Properties

        #region Methods

        public override void Execute( Guid targetInstanceId )
        {
            try
            {
                SPWebApplication spWebApplication = this.Parent as SPWebApplication;
                if ( spWebApplication == null )
                    throw new Exception( "Web application could not be obtained." );

                issueNotifications( );

            }
            catch ( Exception e )
            {
                CustomLoggingService.LogError( CustomLoggingService.Area.TimerJob, e, "Error in Execute" );
            }
        }

        void issueNotifications( )
        {
            DateTime target = configuration.TargetBranchUPSScheduledMaintenanceDate;

            DateTime repeat = configuration.RepeatBranchUPSScheduledMaintenanceNotificationDate;

            StifelHardwareDao dao = new StifelHardwareDao( );
            List<StifelHardware> l = dao.GetScheduled( target );
            foreach ( StifelHardware o in l )
            {
                if ( o.Notifications.Items.Count > 0 )
                {
                    Notification n = o.Notifications.Items[ o.Notifications.Items.Count - 1 ];
                    if ( n.LastNotified.HasValue && n.LastNotified.Value.CompareTo( repeat ) <= 0 )
                    {
                        // TODO: Re-issue notification, e.g. email
                    }
                }
                else
                {
                    // TODO: Issue notification
                }
            }
        }

        #endregion Methods
    }
}